from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.paginator import Paginator
from miles8.blog.models import *
from miles8.blog.forms import CommentForm

def index(request):    
    articles = Article.objects.order_by('-post_time')
    
    p = Paginator(articles, 1)
    
    try: 
        page_index = int(request.GET.get('page', '1'))
        page = p.page(page_index)

    except InvalidPage:
        raise http.Http404
    
    return render_to_response('blog/article_list.html', {'articles':page.object_list,
                                                  'is_paginated': p.num_pages > 1,
                                                  'has_next': page.has_next(),
                                                  'has_previous': page.has_previous(),
                                                  'next_page': page.next_page_number(),
                                                  'previous_page': page.previous_page_number()})

def get_art_by_cate_id(request, cate_id):
    articles = Article.objects.filter(category__id=cate_id).order_by('-post_time')
    selected_category = Category.objects.get(id=cate_id)
    return render_to_response('blog/article_list.html', {'articles':articles, 'selected_category':selected_category})

def get_art_by_art_id(request, art_id):
    article = Article.objects.get(id=art_id)
    comments = Comment.objects.filter(article__id=art_id).order_by('-post_time')
    
    #Update view_count field
    article.view_count += 1
    article.save()
    
    form = CommentForm()    
    
    return render_to_response('blog/article_detail.html', {'article':article, 'comments':comments, 'form':form.as_p()})

def get_art_by_archive_date(request, year, month):
    articles= Article.objects.filter(post_time__startswith=year+'-'+month)
    return render_to_response('blog/article_list.html', {'articles':articles})

def add_comment(request, art_id):
    name = request.POST['name']
    mail = request.POST['mail']
    url = request.POST['url']
    content = request.POST['content'].replace('\r\n', '<br />')
    
    comm = Comment(name=name, mail=mail, url=url, content=content, article_id=art_id)
    comm.save()
    return HttpResponseRedirect("/blog/%s/" % art_id)

def ajax_validator(request):
    if not request.session['captcha']:
        return HttpResponse('Captcha timeout')
    else:
        if request['value'] == request.session['captcha']:
            return HttpResponse('True')
        else:
            return HttpResponse('False')